package com.oda.camera.util;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.os.Build;
import android.os.Environment;
import android.util.Log;

public class LoadImage extends DefaultHandler {
	/**
	 * Tags for xml
	 */
	private static final String TAG_APPS = "oda";
	private static final String TAG_link = "colza";
	private static final String FILE_IMAGE = "colza.xml";
	private static final String DIR_IMAGE="ColzaImage";
	/**
	 * indicate in the tag
	 */
	private boolean inOda = false;
	private boolean incolza = false;

	/**
	 * Liste of path from file
	 */
	private PathFile pictures;
	private String link;
	
	/**
	 * Class for Album
	 */
	private AlbumStorageDirFactory mAlbumStorageDirFactory = null;
	
	

	/**
	 * the constructor
	 */
	public LoadImage() {
		super();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
			mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
		} else {
			mAlbumStorageDirFactory = new BaseAlbumDirFactory();
		}
		File file = new File(getAlbumDir().toString()+"/"+FILE_IMAGE);
		load(file, this);
		
	}

	/**
	 * Call if begin of tag
	 */
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if (qName.equals(TAG_APPS)) {
			pictures = new PathFile();
			inOda = true;
		} else if (qName.equals(TAG_link)) {
			incolza = true;
		}
	}

	/**
	 * Call if end of tag
	 */
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (qName.equals(TAG_APPS)) {
		} else if (qName.equals(TAG_link)) {
			pictures.add(link);
		}
	}

	public void characters(char ch[], int start, int length) {
		if (inOda) {}
		if (incolza) {
			link = new String(ch, start, length);
			incolza=false;
		}
	}

	/**
	 * Load the file
	 * 
	 * @param The
	 *            file
	 * @param this class
	 */
	public void load(File in, LoadImage fromfile) {
		SAXParserFactory saxFactory = SAXParserFactory.newInstance();
		try {
			Log.d("FILE", "" + in);
			SAXParser parser = saxFactory.newSAXParser();
			parser.parse(in, fromfile);
			Log.d("FILE", "Read XML");
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			Log.d("FILE", " NOT found");
			e.printStackTrace();
		}

	}
	
	private File getAlbumDir() {
		File storageDir = null;

		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {

			storageDir = mAlbumStorageDirFactory
					.getAlbumStorageDir(DIR_IMAGE);
		} else {
			Log.v("",
					"External storage is not mounted READ/WRITE.");
		}
		return storageDir;
	}

	/**
	 * @return the pictures
	 */
	public PathFile getPictures() {
		return pictures;
	}

}
